﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using BLL;
using DAL;
using DAL.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ExpressManagement.Areas.BackSys.ServiceTools;
using MqTools;
using Newtonsoft.Json;
using RabbitMQ.Client;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Caching.Memory;
using BLL.Interface;
using DAL.Dao;
using AutoMapper;
using DAL.Models.DTO;

namespace ExpressManagement.Areas.BackSys.Controllers
{
    [Area("BackSys")]
    //[Route("api/[controller]")]
    //[ApiController]
    public class HomeController : Controller
    {
        private static bool isExpire = false; //Session是否超时
        private readonly IDeliverymanImpl _deliverymanImpl;
        private readonly IUserinfoImpl _userinfoImpl;
        //private static BagInfoImpl bagInfoImpl;
        private readonly IManagerImpl _managerImpl;
        //private static ComplaintImpl complaintImpl;
        private readonly IMemoryCache _memoryCache;
        private readonly IMapper _mapper;
        //private readonly ExpressDBContext _dbContext;
        public  ISession Sess { get; }
        public HomeController(IMemoryCache _memoryCache,IUserinfoImpl _userinfoImpl, IManagerImpl _managerImpl, IDeliverymanImpl _deliverymanImpl,ExpressDBContext _dbContext, IHttpContextAccessor httpContextAccessor,DbContextOptions<ExpressDBContext> _dbContextoptions,IMapper _mapper)
        {
            this._memoryCache = _memoryCache;
            this._userinfoImpl = _userinfoImpl;
            this._managerImpl = _managerImpl;
            this._deliverymanImpl = _deliverymanImpl;
            this._mapper = _mapper;
            //this._dbContext = _dbContext;
            Sess = httpContextAccessor.HttpContext.Session;
            DbEntity.BindContext(_dbContext, _dbContextoptions);
        }


        [HttpGet, ActionName("Login")]
        //[ResponseCache(Duration = 10)]
        // GET: BackSys/Login
        public async Task<IActionResult> IdentityValidate()
        {
            //return new RedirectResult("Main");
            if (!string.IsNullOrEmpty(HttpContext.Session.GetString("loginType")) )
            {
                return RedirectToAction("Index", "Welcome");
            }
            return View();
        }






        //[HttpPost]
        //public IActionResult Index(string name, string password, string returnUrl)
        //{
        //    /*
        //      添加验证用户名密码代码
        //    */
        //    MySession.WriteSession("userName", name);
        //    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
        //    {
        //        return Redirect(returnUrl);
        //    }
        //    else
        //    {
        //        return RedirectToAction("Index", "Home");
        //    }
        //}

        // POST: /Account/LogOut

        //public IActionResult Save()
        //{
        //    var sr = new StreamReader(Request.InputStream);
        //    var stream = sr.ReadToEnd();
        //    JavaScriptSerializer js = new JavaScriptSerializer();
        //    var list = js.Deserialize<List<SelectList>>(stream);
        //    if (list.Any())
        //    {
        //        foreach (var item in list)
        //        {

        //        }
        //    }
        //    return PartialView()();
        //}
        //public partial class SelectList
        //{
        //    public int id { get; set; }

        //    public string name { get; set; }

        //    public string text { get; set; }
        //}

        [HttpGet]
        public async Task<IActionResult> Registration()
        {
            return PartialView();
        }

        [HttpPost, ActionName("Registration")]
        public async Task<IActionResult> ProcessRegistration([FromBody]UserDTO entity)
        {

           
            UserInfo user = _mapper.Map<UserInfo>(entity);
      
            //user.Id=impl.GetList().Last().Id + 1;
            //user.UserName = Request.Form["UserName"];
            //user.UserPass = Request.Form["UserPass"];
            //user.TrueName = Request.Form["TrueName"];
            //user.Phone = Request.Form["Phone"];
            //user.Email = Request.Form["Email"];
            //user.Idcard = Request.Form["IdCard"];
            //user.ContactAddress = Request.Form["Address"];
            //user.AddTime = DateTime.Now;
            if (_userinfoImpl.Add(user)) {
                using (MQSender MqSender = new MQSender(Resource.HostName, Resource.VirtualHost, Resource.UserName, Resource.Password, Resource.Exchange,ExchangeType.Topic) )
                {
                     await MqSender.SendMessage(new QueueMessage() { Action = QueueMessage.ActionType.USER_REGISTER, User = user }, Resource.CompanyUserRoute);
                    return Json(1);
                }
               
            }

            return Json(0);
        }



         // public IActionResult Login()
         // {
         //     //Claim类似于身份证的某条内容，一条内容对应一条Claim.例如：民族：汉、籍贯：浙江杭州 此处用的是学校的学生证
         //     var schoolClaims = new List<Claim>()
         //     {
         //         new Claim(ClaimTypes.Name,"李雷"),//姓名
         //         new Claim(ClaimTypes.SerialNumber,"0001"),//学号
         //         //new Claim("Gender","男"),//性别
         //     };
 
         //    //Claim类似于身份证的某条内容，一条内容对应一条Claim.例如：民族：汉、籍贯：浙江杭州 此处用的是社会上的驾照
         //    var drivePass = new List<Claim>()
         //    {
         //        new Claim(ClaimTypes.Name,"李雷"),//姓名
         //        new Claim(ClaimTypes.SerialNumber,"浙A00000"),//车牌号
         //        //new Claim("Driver","GoodJob"),//开车技术怎么样...随便写的
         //    };

         //    //ClaimsIdentity 类似于身份证、学生证。它是有一条或者多条Claim组合而成。这样就是组成了一个学生证和驾照
         //    var schoolIdentity = new ClaimsIdentity(schoolClaims, "school");
         //    var govIdentity = new ClaimsIdentity(drivePass, "gov");

         //    //claimsPrincipal相当于一个人，你可以指定这个人持有哪些ClaimsIdentity（证件）,我指定他持有schoolIdentity、govIdentity那么他就是
         //    //在学校里是学生，在社会上是一名好司机
         //    ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(new[] { schoolIdentity, govIdentity });

         //    //HttpContext上下文登录。会根据你在StartUp.cs文件中配置的services.AddAuthentication("CookiesAuth").AddCookie("CookiesAuth")进行操作
         //    //此处就是增加了Cookies
         //    HttpContext.SignInAsync(claimsPrincipal);
         //   HttpContext.SignOutAsync()
         //    //HttpContext上下文登出,会清除Cookies
         //    //HttpContext.SignOutAsync()
         //    return View("Index");
         //}

        public async Task RegistAuthAndDetail(string role,string userInfoJson,string userName,int id, AuthenticationProperties properties)
        {
            Sess.SetString("loginType", role);
            Sess.SetString("detail", userInfoJson);
            Sess.SetString("userName", userName);
            Sess.SetInt32("userID", id);
            var claims = new List<Claim>();
            //这里的scheme一定要和注入服务的scheme一样
            var identity = new ClaimsIdentity(new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme));
            identity.AddClaim(new Claim(ClaimTypes.Name, userName));
            identity.AddClaim(new Claim(ClaimTypes.SerialNumber, id.ToString()));
            identity.AddClaim(new Claim(ClaimTypes.Role, role));
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), properties);
        }
        public Task SetDetailInfoOnSession(string userInfo,string userName,int id )
        {

            return Task.CompletedTask;
        }


        [HttpPost, ActionName("Login")]
        public async Task<IActionResult> ProcessRequest([FromForm] UserDTO entity)
        {

            UserInfo user = _mapper.Map<UserInfo>(entity);
            //var name = Request.Form["userName"].ToString().Trim();
            //var pass = Request.Form["userPass"].ToString().Trim();
            var claims = new List<Claim>();

            //这里的scheme一定要和注入服务的scheme一样
            var identity = new ClaimsIdentity(new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme));
            //自定义的claim信息
            AuthenticationProperties properties = new AuthenticationProperties()
            {
                //设置cookie票证的过期时间
                ExpiresUtc = DateTime.Now.AddDays(1),
                //RedirectUri = model.ReturnUrl
            };
            var userInfo = _userinfoImpl.Login(user.UserName, user.UserPass);
            if (userInfo != null)
            {
                await RegistAuthAndDetail(Resource.IdentityUser,JsonConvert.SerializeObject(userInfo), userInfo.UserName, userInfo.Id,  properties);
                return Json(1);
            }
            var managerInfo = _managerImpl.Login(user.UserName, user.UserPass);
            if (managerInfo != null)
            {
                await RegistAuthAndDetail(Resource.IdentityManager, JsonConvert.SerializeObject(managerInfo), managerInfo.UserName, managerInfo.Id,  properties);
                return Json(1);
            }
            var deliverymanInfo = _deliverymanImpl.Login(user.UserName, user.UserPass);
            if (deliverymanInfo != null)
            {
                await RegistAuthAndDetail(Resource.IdentityDeliveryman, JsonConvert.SerializeObject(deliverymanInfo), deliverymanInfo.UserName, deliverymanInfo.Id,  properties);
                return Json(1);
            }
            return Json(0);

        }



        protected void Session_End(object sender, EventArgs e)
        {
            isExpire = true;

            //Session.Abandon();
        }
        //protected void Application_BeginRequest(object sender, EventArgs e)
        //{
        //    bool IsAjax = Request.IsAjaxRequest();
        //    if (isExpire && (IsAjax == false))
        //    {
        //        isExpire = false;
        //        Response.Write("<script languge='javascript'>alert('用户信息已过期，请重新登录');window.parent.location.href='/Home/LogOut';</script>");
        //        Response.End();
        //        //Response.Redirect("~/Home/LogOut");
        //    }
        //}

    }
}